<?php
function site($site){
	$data = [];
	$num = 0;
	foreach ($site as $k =>$v){

		$data[$num]['id'] = $k;
		$data[$num]['name'] = $v;
		$num += 1;
	}
	return $data;
}


function msg_check($content){

	$config  = get_addon_config('third');

	$APPID     = $config['wechatMini']['app_id'];
	$APPSECRET = $config['wechatMini']['app_secret'];

	//获取access_token
	$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

	//缓存access_token
	if (Cache('access_token')) {

		$ACCESS_TOKEN = Cache('access_token');

	} else {

		$json = httpRequest($access_token);
		$json = json_decode($json, true);

		Cache('access_token', $json['access_token'], 3000);

		$ACCESS_TOKEN = $json["access_token"];
	}

	$params = [
		'access_token' => $ACCESS_TOKEN,
	];
	$request_params = to_url_params($params);
	$url = "https://api.weixin.qq.com/wxa/msg_sec_check?" . $request_params;

	$data = json_encode(['content'=>$content],JSON_UNESCAPED_UNICODE);//网上看到的基本都是直接让中文给json转义了，实测json转义后无法检测出实际违规内容

	$result = json_decode(curl_request($url, $data, true),true);
	//返回数据自行根据自己需要进行判断
	return $result;
}


//参数处理
function to_url_params($params){
	$buff = "";
	foreach ($params as $k => $v) {
		if ($k != "sign") {
			$buff .= $k . "=" . $v . "&";
		}
	}
	$buff = trim($buff, "&");
	return $buff;
}

function curl_request($url = '', $postData = '', $options = array())
{

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	if (!empty($postData)) {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
	}
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
	if (!empty($options)) {
		//curl_setopt_array($ch, $options);
	}
	//https请求 不验证证书和host
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;

}

//把请求发送到微信服务器换取二维码
// function httpRequest($url, $data = '', $method = 'GET')
//{
//
//	$curl = curl_init();
//	curl_setopt($curl, CURLOPT_URL, $url);
//	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
//	curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//	curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
//	if ($method == 'POST') {
//		curl_setopt($curl, CURLOPT_POST, 1);
//		if ($data != '') {
//			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//		}
//	}
//
//	curl_setopt($curl, CURLOPT_TIMEOUT, 30);
//	curl_setopt($curl, CURLOPT_HEADER, 0);
//	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//	$result = curl_exec($curl);
//	curl_close($curl);
//
//	return $result;
//}